#coding=utf-8
import datetime
import os

import time
import traceback

from loguru import logger
from playwright.sync_api import sync_playwright
import douyin.dou_yin_common as dou_yin_common


def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group

def dy_main(host, account_list):
    try:
        store_id_list = list(set(map(lambda x: x['storeId'], account_list)))
        logger.info('正在运行抖音RPA...')
        need_login = True
        with sync_playwright() as playwright:
            for store_id_index, store_id in enumerate(store_id_list):
                store_job_list = list(filter(lambda x: x['storeId'] == store_id, account_list))
                logger.info("开始下载店铺的账单：【{}】".format(store_job_list[0]['account']))
                has_store = False
                try:
                    if need_login:
                        dy_func = dou_yin_common.DY(host, playwright, 'haiwangou-key', True)
                        # 第一个店铺需要登录后选择店铺
                        dy_func.login(store_job_list[0])
                        logger.info("正在选择店铺：【{}】".format(store_job_list[0]['account']))
                        store_list = []
                        div_list = dy_func.page.query_selector_all('div')
                        for div in div_list:
                            class_name = div.get_attribute('class')
                            if class_name is not None and 'index_introName__' in class_name:
                                store_list.append(div)
                        for store in store_list:
                            if store.text_content() == store_job_list[0]['account']:
                                store.click()
                                time.sleep(5)
                                # self.wait(self.page)
                                logger.info("登录店铺...")
                                has_store = True
                                break
                    else:
                        # 切换下一个店铺
                        has_store = dy_func.change_store(store_job_list[0])
                    if not has_store:
                        message = f'店铺名称【{store_job_list[0]["account"]}】不存在'
                        logger.info(message)
                        log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                        dy_func.update_log(log_id_list, message)
                        dy_func.close()
                        continue
                    dy_func.after_login_check_dialog()
                    # 按照周期分组，按每个周期循环运行，每跑完一个周期上传一次
                    job_group = group_by_period(store_job_list)
                    for period, job_list in job_group.items():
                        param_list = []
                        file_list = []
                        logger.info(f'正在下载周期【{period}】的账单...')
                        check, shop_id = dy_func.check_store_id(job_list[0]['innerOutlineStoreCode'])
                        if not check:
                            if shop_id is None:
                                message = f'店铺【{store_job_list[0]["account"]}】没有权限验证店铺ID'
                                logger.info(message)
                                log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                                dy_func.update_log(log_id_list, message)
                                dy_func.close()
                                break
                            else:
                                message = f'店铺ID【{job_list[0]["innerOutlineStoreCode"]}】和平台上的店铺ID【{shop_id}】不一致'
                                logger.info(message)
                                log_id_list = list(set(map(lambda x: x['logId'], store_job_list)))
                                dy_func.update_log(log_id_list, message)
                                dy_func.close()
                                break
                        for item in job_list:
                            period = str(item['period']).replace('-', '/')
                            if item['accountType'] == '结算账单':
                                s_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                # 下载抖音结算单
                                bill_file = dy_func.download_bill(item, period, s_time)
                                if bill_file is not None:
                                    if bill_file == -1:
                                        message = f'子账号没有权限'
                                        logger.info(message)
                                        log_id_list = [item['logId']]
                                        dy_func.update_log(log_id_list, message)
                                    else:
                                        file_list.append(bill_file)
                                        dir_path, file_name = os.path.split(bill_file)
                                        param_list.append({'orderType': '结算账单', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': s_time})
                                else:
                                    param_list.append({'orderType': '结算账单', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': s_time})
                            elif item['accountType'] == '资金流水':
                                s_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                # 下载资金流水
                                bill_file = dy_func.download_fund_flow(item, period)
                                if bill_file is not None:
                                    if bill_file == -1:
                                        message = f'子账号没有权限'
                                        logger.info(message)
                                        log_id_list = [item['logId']]
                                        dy_func.update_log(log_id_list, message)
                                    else:
                                        file_list.append(bill_file)
                                        dir_path, file_name = os.path.split(bill_file)
                                        param_list.append({'orderType': '资金流水', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': s_time})
                                else:
                                    param_list.append({'orderType': '资金流水', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': s_time})
                            elif item['accountType'] == '结算账单总数':
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                bill_count = dy_func.get_bill_count(period)
                                param_list.append({'orderType': '结算账单总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            elif item['accountType'] == '资金流水总数':
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                bill_count = dy_func.get_fund_flow_count(period)
                                param_list.append({'orderType': '资金流水总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if len(param_list) > 0:
                            # 编码字符串
                            coding_param = dy_func.encode_param(param_list)
                            # 上传文件
                            uri = "api/v1/dyBill/dyBillRPAImport/{}".format(item['storeCode'])
                            dy_func.upload_file(uri, coding_param, file_list)
                    # 下一个店铺不用重新登录，直接切换即可
                    need_login = False
                except:
                    logger.info(traceback.format_exc())
                    dy_func.close()
                    need_login = True
    except:
        logger.info(traceback.format_exc())
